#!/usr/bin/python
import subprocess
import sys
import argparse
import re
import xml.etree.ElementTree as ET
import os

parser = argparse.ArgumentParser(description='Test Bed Info help:')
parser.add_argument('-t', help= "Transaction number")

argu = parser.parse_args()

if argu.t == None:
    print ("Please enter txn number and stream to look up. Exiting...")
    sys.exit(0)

txn    = argu.t

accurev_login_handle = subprocess.Popen("accurev info", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell = True)
for lines in accurev_login_handle.stdout.readlines():
    if re.search(r"\(not",lines):
        print ("Please login into accurev")
        sys.exit(0)

try:
    data = os.popen("accurev hist -t %s -p upc -fx"%(txn)).read()
    
except Exception as err:
    print (err)
    sys.exit(0)

if data == '':
    print("Txn not found or invalid txn")
    sys.exit(0)

parser = ET.XMLParser(encoding="utf-8")
root = ET.fromstring(data,parser=parser)

issue_list = []

for capture in root.iter('issueNum'):
    issue_list.append(capture.text)

issue_list = list(set(issue_list))
     
ar_list = []
summary = []

for issues in issue_list:
    ar_handle = subprocess.Popen("/c4shares/auto/devutils/bin/lookup_issue --issue-type accurev --remedy --summary %s"%(issues),shell= True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for ar in ar_handle.stdout.readlines():
        if re.search(r"AR\d+",ar):
            ar_serach = re.search(r"AR\d+",ar)
            ar_list.append(ar_serach.group(0).strip())
        else:
            summary.append(ar)
                   
if len(ar_list) == 0:
        sys.exit(0)

print ("{0:30s} {1:30s}".format('AR', 'Description'))
print ("{0:30s} {1:30s}".format('--', '------------'))


count = 0
while count < len(ar_list):
    print("{0:30s} {1:30s}".format(ar_list[count], summary[count]))
    count += 1
